<?php


namespace app\admin\controller;

use app\admin\model\Config as ConfigModel;
use app\admin\model\ConfigGroup;
use app\admin\service\ConfigGroupService;
use app\admin\service\ConfigService;
use app\common\controller\BaseAdmin;
use think\facade\Cache;

class Config extends BaseAdmin
{
    public function index(){
        if ($this->request->isAjax()){
            //获取搜索条件
            $data =$this->request->except(['page'],'get');

            $model = new ConfigModel();
            $list = $model->withSearch($this->searchFields($data),$this->searchData($data))
                ->order('id','desc')
                ->paginate($data['limit'], false);

            return $this->tableJson($list->getCollection(), $list->total());
        }

        $groupList = ConfigGroup::column('name,title');
        $this->assign('groupList',array_column($groupList,'title','name'));
        return $this->fetch();
    }

    /**
     * 添加编辑配置
     */
    public function edit(){
        if ($this->request->isAjax()){

            $data = $this->request->param();
            //编辑或者添加数据
            $scene = empty($data['id'])?'add':'edit';
            return json(ConfigService::storeConfig($data,$scene));
        }

        //分组select
        $groupList = ConfigGroup::column('name,title');
        $this->assign('groupList',array_column($groupList,'title','name'));

        $id = $this->request->get('id');
        if ($id){
            $list = ConfigModel::where('id', $id)->find();
            $this->assign('list', $list);
        }
        return $this->fetch();
    }

    /**
     * 删除配置
     */
    public function remove(){
        if ($this->request->isAjax()){
            $ids = $this->request->param('ids');
            ConfigModel::destroy($ids);
            $this->success('删除成功');
        }else{
            $this->error('非法请求');
        }
    }

    /**
     * 配置审核
     */
    public function change(){
        $id = $this->request->param('id');
        $model = ConfigModel::find($id);
        $model->state = $this->request->param('state');
        if ($model->save()){
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }


    /**
     * 分组列表
     */
    public function group(){
        if ($this->request->isAjax()){
            //获取搜索条件
            $data =$this->request->except(['page'],'get');

            $model = new ConfigGroup();
            $list = $model->withSearch($this->searchFields($data),$this->searchData($data))
                ->order('id','desc')
                ->paginate($data['limit'], false);

            return $this->tableJson($list->getCollection(), $list->total());
        }
        return $this->fetch();
    }

    /**
     * 添加编辑分组
     */
    public function edit_group(){
        if ($this->request->isAjax()){

            $data = $this->request->param();
            //编辑或者添加数据
            $scene = empty($data['id'])?'add':'edit';
            return json(ConfigGroupService::storeGroup($data,$scene));
        }

        $id = $this->request->get('id');
        if ($id){
            $list = ConfigGroup::where('id', $id)->find();
            $this->assign('list', $list);
        }
        return $this->fetch();
    }

    /**
     * 删除分组
     */
    public function remove_group(){
        if ($this->request->isAjax()){
            $ids = $this->request->param('ids');
            $config = ConfigGroup::where('id','in',$ids)->column('name');

            $check = ConfigModel::where('group','in',$config)->find();
            if ($check){
                $this->error('改分组下面有配置不能删除');
            }else{
                ConfigGroup::destroy($ids);
                $this->success('删除成功');
            }
        }else{
            $this->error('非法请求');
        }
    }

    /**
     * 更新缓存
     */
    public function cache(){
        $group = $this->request->param('group','');
        if (!empty($group)){

            //清除对应分组的缓存
            Cache::tag('config_'.$group)->clear();
        }else{

            //清除所有的缓存
            $group = ConfigGroup::column('name');
            foreach ($group as $item){
                Cache::tag('config_'.$item)->clear();
            }
        }
        $this->success( '清除成功');
    }

    /**
     * 系统设置
     * @return string
     */
    public function system(){
        if ($this->request->isAjax()){
            $data = $this->request->param();
            foreach ($data as $key=>$group){
                $config = ConfigModel::where('group',$key)->select();
                foreach ($config as $item){
                    $item->value = $group[$item->code];
                    $item->save();
                }
            }
            $this->success('修改成功');
        }

        //分组
        $group = ConfigGroup::where('system',1)->select()->toArray();
        $this->assign('group',$group);

        //每个分组下面的配置
        foreach ($group as &$item){
           $config = ConfigModel::where('group',$item['name'])
                ->where('state',1)
                ->field('code,value,remark,type,item')
                ->select()
                ->toArray();
            foreach ($config as &$value) {
               if ($value['type'] == 'select') {
                   //将$value['select']的 key:value|key:value或者value|value格式转换成数组
                   $lists = explode('|',$value['item']);
                   foreach ($lists as $v){
                        $temp  = explode(':',$v);
                        if (count($temp) == 1) {
                            $value['items'][$v] = $v;
                        }else{
                            $value['items'][$temp[0]] = $temp[1];
                        }
                   }
               }
            }
            $item['config'] = $config;
        }
        $this->assign('list',$group);
        return $this->fetch();
    }

    /**
     * 脚本配置
     * @return string
     */
    public function plugin(){
        if ($this->request->isAjax()){
            $data = $this->request->param();
            $version = ConfigModel::where('group','plugin')->select();
            foreach ($version as $item){
                $item->value = $data[$item->code];
                $item->save();
            }
            $this->success('修改成功');
        }

        $version = ConfigModel::where('group','plugin')->column('code,value');
        $list = array_column($version,'value','code');
        $this->assign('list',$list);
        return $this->fetch();
    }

}
